package cqrtplm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.dto.RtTestRequirementsDTO;
import cqrtplm.entity.RtTestRequirementsDO;
import cqrtplm.mapper.ProcessNumberMapper;
import cqrtplm.mapper.RtTestRequirementsMapper;
import cqrtplm.service.RtTestRequirementsService;
import cqrtplm.vo.RTEngraveDemandStatusVO;
import cqrtplm.vo.StatusInfoDetailContentVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 博
 * @description 针对表【rt_test_requirements】的数据库操作Service实现
 * @createDate 2025-06-03 15:13:56
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class RtTestRequirementsServiceImpl implements RtTestRequirementsService {

    @Resource
    private ProcessNumberMapper processNumberMapper;
    @Resource
    private RtTestRequirementsMapper rtTestRequirementsMapper;
    @Resource
    private SnowflakeIdComponent snowIdGenerator;

    @Override
    public ResponseResult createRtTestRequirementsDO(RtTestRequirementsDTO dto) {
        try {
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                return ResponseResult.fail("401", "用户未登录");
            }
            if (dto == null || dto.getTestRequirements() == null) {
                return ResponseResult.fail("400", "请求参数不能为空");
            }
            Integer b = rtTestRequirementsMapper.selectByTestRequirments(dto.getTestRequirements(),null);
            if (b>0) {
                return ResponseResult.fail("500", "测试需求已存在");
            }
            dto.setId(String.valueOf(snowIdGenerator.getInstance().nextId()));
            dto.setCode(new BigInteger(processNumberMapper.getNextProcessNumber()));
            dto.setCreateDate(new Date());
            dto.setCreateUser(String.valueOf(user.getOid()));
            dto.setCreateUserCname(user.getName());
            dto.setDr(0);
            dto.setStopFlag("0");
            // 修改为支持集合拼接
            if (dto.getTypeCodeList() != null && !dto.getTypeCodeList().isEmpty()) {
                String typeCodeStr = String.join(",", dto.getTypeCodeList());
                dto.setTypeCode(typeCodeStr);
            } else if (dto.getTypeCode() != null) {
                dto.setTypeCode(dto.getTypeCode());
            }
            int result = rtTestRequirementsMapper.insertRtTestRequirementsDTO(dto);
            return result > 0
                    ? ResponseResult.success("新建测试需求成功")
                    : ResponseResult.fail("500", "新建测试需求失败");

        } catch (Exception e) {
            log.error("新建测试需求异常", e);
            return ResponseResult.fail("500", "新建测试需求异常: " + e.getMessage());
        }
    }

    @Override
    public ResponseResult deleteRtTestRequirementsDOByOid(String[] ids) {
        if (ids == null || ids.length == 0) {
            return ResponseResult.fail("500", "传入的ids为空");
        }

        int deletedCount = rtTestRequirementsMapper.deleteByIds(ids);
        if (deletedCount <= 0) {
            return ResponseResult.fail("500", "未找到匹配的数据进行删除");
        }
        return ResponseResult.success("删除成功");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateRtTestRequirementsDO(RtTestRequirementsDTO dto) {
        try {
            if (dto == null) {
                return ResponseResult.fail("400", "请求参数不能为空");
            }
            if (dto.getId() == null) {
                return ResponseResult.fail("400", "测试需求ID不能为空");
            }

            Integer b = rtTestRequirementsMapper.selectByTestRequirments(dto.getTestRequirements(),dto.getId());
            if(b>0){
                return ResponseResult.fail("500", "测试需求已存在");
            }

            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                return ResponseResult.fail("401", "用户未登录");
            }
            String userOidStr = String.valueOf(user.getOid());
            dto.setUpdateDate(new Date());
            dto.setUpdateUserCname(user.getName());
            dto.setUpdatePerson(userOidStr);
            dto.setUpdateUser(userOidStr);
            // 修改为支持集合拼接
            if (dto.getTypeCodeList() != null && !dto.getTypeCodeList().isEmpty()) {
                String typeCodeStr = String.join(",", dto.getTypeCodeList());
                dto.setTypeCode(typeCodeStr);
            } else if (dto.getTypeCode() != null) {
                dto.setTypeCode(dto.getTypeCode());
            }
            if (dto.getStopFlag() != null) {
                dto.setStopFlag(dto.getStopFlag());
                if ("1".equals(dto.getStopFlag())) {
                    dto.setStopDate(new Date());
                    dto.setStopPerson(userOidStr);
                } else {
                    dto.setStopDate(null);
                    dto.setStopPerson("");
                }
            }
            int result = rtTestRequirementsMapper.updateById(dto);
            return result > 0
                    ? ResponseResult.success("修改测试需求成功")
                    : ResponseResult.fail("500", "修改测试需求失败");

        } catch (Exception e) {
            log.error("修改测试需求异常", e);
            return ResponseResult.fail("500", "修改测试需求异常: " + e.getMessage());
        }
    }

    @Override
    public PageInfo<RtTestRequirementsDO> selectAllByRtTestRequirementsDTO(RtTestRequirementsDTO rtTestRequirementsDTO,
                                                                           int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<RtTestRequirementsDO> list = rtTestRequirementsMapper.selectAllByRtTestRequirementsDTO(
                rtTestRequirementsDTO);
        for (RtTestRequirementsDO rtTestRequirementsDO : list){
            if (rtTestRequirementsDO.getTypeCode() != null && !rtTestRequirementsDO.getTypeCode().isEmpty()) {
                List<String> typeCodeList = Arrays.asList(rtTestRequirementsDO.getTypeCode().split(","));
                rtTestRequirementsDO.setTypeCodeList(typeCodeList);
            } else {
                rtTestRequirementsDO.setTypeCodeList(Collections.emptyList());
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * @return
     */
    @Override
    public List<RtTestRequirementsDO> queryAll() {
        List<RtTestRequirementsDO> list = rtTestRequirementsMapper.selectAllByStatusInfo();
        return list;
    }

    @Override
    public List<StatusInfoDetailContentVO> selectStatusInfoDetailContentVO(String producttype) {
        return rtTestRequirementsMapper.selectStatusInfoDetailContentVO(producttype);
    }

    @Override
    public ResponseResult queryStatusInfoByTestCode(String testCode) {
        return ResponseResult.success( rtTestRequirementsMapper.queryStatusInfoByTestCode(testCode));
    }


}




